import { HtmlNode, HtmlNodeModel } from '@logicflow/core';

class TableModel extends HtmlNodeModel {
  setAttributes() {
    // 禁止节点文本编辑
    this.text.editable = false;
    const {
      properties: { width, height },
    } = this;
    this.width = width || 300;
    this.height = height || 200;
  }

  getDefaultAnchor(): { x: number; y: number; id: string }[] {
    return [];
  }
}
class Table extends HtmlNode {
  setHtml(rootEl: HTMLElement) {
    const {
      properties: { title, columns = [], data = [], fontSize },
    } = this.props.model;

    const el = document.createElement('div');
    el.className = 'table-wrapper';
    const html = `
      <table class="table" style="font-size: ${fontSize}px;">
        ${title ? `<caption class="table-head">${title}</caption>` : ' '}
        <thead>
          <tr class="table-row">
            ${columns
              .map(
                (o: any) => `
                  <td class="table-cell" width="${o.width}">${o.label}</td>
                `
              )
              .join('')}
          </tr>
        </thead>
        <div class="table-body">
          ${data
            .map(
              (o: any) => `
                <tr class="table-row">
                  ${columns
                    .map(
                      (p: any) => `
                        <td class="table-cell">${o[p.value] || ''}</td>
                      `
                    )
                    .join('')}
                </tr>
              `
            )
            .join('')}
        </div>
      </table>
    `;
    el.innerHTML = html;
    // 需要先把之前渲染的子节点清除掉。
    rootEl.innerHTML = '';
    rootEl.appendChild(el);
  }
}

export default {
  type: 'Table',
  view: Table,
  model: TableModel,
};
